package com.meitianhui.convenitenbuy.hyphenate.ui;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hyphenate.util.EasyUtils;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseArrayResponse;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.http.ResponseObserver;
import com.meitianhui.convenitenbuy.hyphenate.runtimepermissions.PermissionsManager;
import com.meitianhui.convenitenbuy.main.model.bean.HyphenateInfo;
import com.meitianhui.convenitenbuy.module.mine.adapter.GroupMemberAdapter;
import com.meitianhui.convenitenbuy.module.mine.http.MineApiDataSource;
import com.meitianhui.convenitenbuy.module.mine.model.UserUrlBean;
import com.meitianhui.convenitenbuy.module.mine.model.rxbusBean.ChatMenuEventBean;
import com.meitianhui.convenitenbuy.util.PreferenceUtils;
import com.meitianhui.convenitenbuy.util.RxBus;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.hyphenate.util.DensityUtil.dip2px;

/**
 * chat activity，EaseChatFragment was used {@link #}
 */
public class ChatActivity extends BaseActivity {
    public static ChatActivity activityInstance;
    private EaseChatFragment chatFragment;
    String toChatUsername, mTilte;
    private List<UserUrlBean> mUserUrlBeanList = new ArrayList<UserUrlBean>();

    PopupWindow menuPopupWindow;
    private GroupMemberAdapter mGroupMemberAdapter;
    private RecyclerView mRlvChatPop;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.em_activity_chat);
        activityInstance = this;
        //get user id or group id
        toChatUsername = getIntent().getExtras().getString("userId");

        mTilte = getIntent().getExtras().getString("groupName");
        //use EaseChatFratFragment
        chatFragment = new ChatFragment();
        //pass parameters to chat fragment
        chatFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager().beginTransaction().add(R.id.container, chatFragment).commit();

        //群聊
        mGroupMemberAdapter = new GroupMemberAdapter(mUserUrlBeanList);
        //群聊右上角的菜单的点击事件
        initListener();
        int chatType = getIntent().getIntExtra("chatType", 1);
        if (chatType == Constants.CHATTYPE_GROUP) {
            //如果是群组模式
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("group_id", toChatUsername);
            } catch (Exception e) {
            }

            MineApiDataSource.getInstance().getMsgGroupMember(InfoProvider.getUserToken(this).getUser_token(), "chat.getChatGroupUsers", jsonObject.toString()).subscribe(new ResponseObserver<BaseArrayResponse<UserUrlBean>>(this) {
                @Override
                public void onSuccess(BaseArrayResponse<UserUrlBean> userUrlBeanList) {
                    ArrayList<UserUrlBean> userUrlList = userUrlBeanList.data;
                    mUserUrlBeanList.add(userUrlList.get(0));
                }

                @Override
                public void onFail(int code, String msg) {
                    super.onFail(code, msg);
                    //mView.showError(msg);
                }
            });

        } else if (chatType == Constants.CHATTYPE_SINGLE) {


        }


    }

    private void initListener() {
        Disposable subscribe = RxBus.get().toFlowable(ChatMenuEventBean.class).subscribe(new Consumer<ChatMenuEventBean>() {
            @Override
            public void accept(ChatMenuEventBean chatMenuEventBean) throws Exception {
                if (chatMenuEventBean.type.equals("menuClick")) {
                    //点击了右上的菜单按钮
                    initMenuPopupWindow();
                }
            }
        });
        mCompositeDisposable.add(subscribe);

    }

    private void initMenuPopupWindow() {
        View popupWindowView = View.inflate(ChatActivity.this, R.layout.chat_pop_member, null);
        mRlvChatPop = (RecyclerView) popupWindowView.findViewById(R.id.rlv_chat_pop);
        mRlvChatPop.setAdapter(mGroupMemberAdapter);
        mRlvChatPop.setLayoutManager(new GridLayoutManager(this, 3));
        mGroupMemberAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //点击群聊用户头像跳转到单聊界面
                UserUrlBean userUrlBean = mUserUrlBeanList.get(position);
                if (TextUtils.isEmpty(userUrlBean.getIm_user_id())) {

                    HyphenateInfo hyphenateInfo = (HyphenateInfo) PreferenceUtils.readObject(ChatActivity.this, Constants.HYPHENATE_INFO);
                    if (hyphenateInfo != null)
                        if (userUrlBean.getIm_user_id().equals(hyphenateInfo.getIm_user_id())) {
                            //当点击为用户自己头像时，
                            return;
                        } else {
                            Intent intent = new Intent(ChatActivity.this, ChatActivity.class);
                            intent.putExtra("userId", userUrlBean.getIm_user_id());
                            intent.putExtra("groupName", userUrlBean.getNickname());
                            startActivity(intent);
                        }
                    menuPopupWindow.dismiss();
                }
            }
        });

        menuPopupWindow = new PopupWindow(popupWindowView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT, true);
        menuPopupWindow.setAnimationStyle(R.style.AnimationRightFade);

        //菜单背景色
        ColorDrawable dw = new ColorDrawable(Color.parseColor("#cc000000"));
        menuPopupWindow.setBackgroundDrawable(dw);
        menuPopupWindow.showAtLocation(findViewById(R.id.container), Gravity.RIGHT, 0, dip2px(ChatActivity.this, 100));
        //关闭事件
        menuPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityInstance = null;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // make sure only one chat activity is opened
        String username = intent.getStringExtra("userId");
        if (toChatUsername.equals(username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }

    }

    @Override
    public void onBackPressed() {
        chatFragment.onBackPressed();

        if (EasyUtils.isSingleActivity(this)) {
            this.finish();
        }
    }

    public String getToChatUsername() {
        return toChatUsername;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }
}
